package cn.chencaiju.day13;

import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class ClientFx extends Application{
	private Socket socket;
	private DataOutputStream os;
	
	@Override
	public void start(Stage primaryStage) throws Exception {
		VBox box=new VBox(10);//容器内行间间隔
		box.setPadding(new Insets(10));//容器内控件与边缘的距离
		TextArea ta=new TextArea();
		VBox.setVgrow(ta, Priority.ALWAYS);//填满VB
		TextField tf=new TextField();
		box.getChildren().add(ta);
		box.getChildren().add(tf);
		
		Scene scene=new Scene(box);
		primaryStage.setScene(scene);
		tf.setOnKeyPressed((event)->{
			KeyCode code = event.getCode();
			if(code==KeyCode.ENTER&&tf.getText()!=null) {
				ta.appendText(tf.getText()+"\n");
				if ("88".equals(tf.getText())) {
					// 客户端结束的逻辑处理
					Utils.closeQuietly(os);
					Utils.closeQuietly(socket);
					System.exit(0);
				}				
				try {
					os.writeUTF(tf.getText());
					os.flush();
					tf.clear();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		});
		
		primaryStage.show();
		
		openSocket();
	}
	private void openSocket() {
		try {
			socket = new Socket("127.0.0.1", 6666);
			os = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
			System.out.println("和服务器已经连上了。。。");
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}	
		
	}
	@Override
	public void stop() throws Exception {
		super.stop();
		Utils.closeQuietly(os);
		Utils.closeQuietly(socket);
	}
	public static void main(String[] args) {
		launch(args);
	}

}
